import {createRouter, createWebHashHistory} from "vue-router";
//登录
import login from "../views/login";
//注册
import register from "../views/register";
//主页
import page from "../views/page";
//用户
import user from "../views/user";
//角色
import role from "../views/role";
//订单
import orders from "../views/orders";
//地址
import address from "../views/address";

const routes = [
    //登录
    {
        path: "/",
        name: "login",
        component: login,
        meta: {
            title: "用户登录",
            requireAuth: true,
        },
    },
    //注册
    {
        path: "/register",
        name: "register",
        component: register,
        meta: {
            title: "用户注册",
            requireAuth: true,
        },
    },
    //主页
    {
        path: "/page",
        name: "page",
        component: page,
        //主页
        children: [
            //用户管理
            {
                path: "/user",
                name: "user",
                component: user,
                meta: {
                    title: "用户管理",
                },
            },
            //订单管理
            {
                path: "/orders",
                name: "orders",
                component: orders,
                meta: {
                    title: "订单管理",
                },
            },
            //角色管理
            {
                path: "/role",
                name: "role",
                component: role,
                meta: {
                    title: "角色管理",
                },
            },
            //地址管理
            {
                path: "/addrerss",
                name: "address",
                component: address,
                meta: {
                    title: "地址管理",
                },
            },
        ],
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

//登录拦截
router.beforeEach((to, from, next) => {
    window.document.title =
        to.meta.title == undefined ? "悦跑校园-管理端" : to.meta.title;
    if (!to.meta.requireAuth) {
        var token = sessionStorage.getItem("token");
        if (token != null) {
            next();
        } else {
            next({
                name: "login",
            });
        }
    } else {
        next();
    }
});
export default router;
